package searchkeyword

import (
	"context"
	// "fmt"
	"strings"
	"time"

	"mall/common/globalkey"
	"mall/common/modelx"
	"mall/common/resultx"
	"mall/common/utils/pointy"
	"mall/service/backend/model"
	"mall/service/backend/rpc/internal/svc"
	"mall/service/backend/rpc/internal/utils/errorhandler"
	"mall/service/backend/rpc/types/backend"

	// "github.com/sirupsen/logrus"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetSearchKeywordListLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetSearchKeywordListLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetSearchKeywordListLogic {
	return &GetSearchKeywordListLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetSearchKeywordListLogic) GetSearchKeywordList(in *backend.BaseListReq) (*backend.SearchKeywordListResp, error) {
	// logrus.Info(fmt.Sprintf("GetSearchKeywordList BaseListReq: %+v", in))
	// Limit:10  Preload:"searchKeyword:Id,Title,LinkType,LinkUrl,ObjectType,ObjectId"  Filter:"Status,equalTo:1;Type,equalTo:1"  VisitorId:10021  PlatformId:1

	if in.Filter == nil || len(*in.Filter) == 0 {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	preloadMap, eagerLoadMap := modelx.ParsePreloadAndEagerLoad(in.Preload, in.EagerLoad)
	// logrus.Info(fmt.Sprintf("GetSearchKeywordList preloadMap: %+v", preloadMap))
	// map[searchKeyword:[Id Title LinkType LinkUrl ObjectType ObjectId]]
	// logrus.Info(fmt.Sprintf("GetSearchKeywordList eagerLoadMap: %+v", eagerLoadMap))
	// map[]

	searchKeywordEntityName := model.RpcEntityNames.SearchKeyword
	if _, ok := model.RpcEntityPreloadMap[searchKeywordEntityName]; !ok {
		return &backend.SearchKeywordListResp{}, nil
	}

	searchKeywordRepositoryName := model.RepositoryNames.SearchKeyword
	columnMap, ok := model.RepositoryPreloadMap[searchKeywordRepositoryName]
	if !ok {
		return &backend.SearchKeywordListResp{}, nil
	}

	var selectCols []string
	if preloadFields, ok := preloadMap[searchKeywordEntityName]; ok {
		selectCols = modelx.ParseSelectColumns(preloadFields, columnMap)
	}

	filterMap := modelx.ParseFilter(in.Filter, columnMap)
	// logrus.Info(fmt.Sprintf("GetSearchKeywordList filterMap: %+v", filterMap))
	// map[status:map[equalTo:[1]] type:map[equalTo:[1]]]
	if filterMap == nil {
		return nil, resultx.StatusError(resultx.REUQEST_PARAM_ERROR, "")
	}

	now := time.Now()
	filterMap[model.SearchKeywordColumns.StartedAt] = map[string][]any{
		"lessThanOrEqualTo": {now},
	}
	filterMap[model.SearchKeywordColumns.EndedAt] = map[string][]any{
		"moreThan": {now},
	}

	orderBy := modelx.ParseSorter(in.Sorter, columnMap)
	// logrus.Info(fmt.Sprintf("GetSearchKeywordList orderBy: %s", orderBy))
	//
	res, count, err := l.svcCtx.SearchKeyword.GetList(l.ctx, model.M{
		"offset":  in.Offset,
		"limit":   in.Limit,
		"orderBy": orderBy,
		"select":  strings.Join(selectCols, ","),
	}, 2, filterMap)
	if err != nil {
		return nil, errorhandler.DefaultRepositoryError(l.Logger, err, in)
	}

	hasNextPage, hasPreviousPage := modelx.ParseCount(count)
	resp := &backend.SearchKeywordListResp{
		HasNextPage:     &hasNextPage,
		HasPreviousPage: &hasPreviousPage,
	}

	var total int64
	if len(res) > 0 {
		subEntitySettingMap := make(map[string]map[string]*model.ColumnSetting)
		if eagerLoadEntities, ok := eagerLoadMap[searchKeywordEntityName]; ok {
			for _, entity := range eagerLoadEntities {
				if entity == "total" {
					_, total, err = l.svcCtx.SearchKeyword.GetList(l.ctx, model.M{}, 0, filterMap)
					if err != nil {
						total = 0
					}
					continue
				}

				if entitySettingMap, ok := model.RpcEntityPreloadMap[entity]; ok {
					subEntitySettingMap[entity] = entitySettingMap
				}
			}
		}

		for _, v := range res {
			var sort *uint32
			if v.Sort != uint16(globalkey.SystemDefaultSort) {
				sort = pointy.GetPointer(uint32(v.Sort))
			}
			resp.List = append(resp.List, &backend.SearchKeywordInfo{
				Id:         &v.ID,
				Type:       pointy.GetPointer(uint32(v.Type)),
				Title:      &v.Title,
				ObjectId:   &v.ObjectID,
				ObjectType: pointy.GetPointer(uint32(v.ObjectType)),
				LinkType:   pointy.GetPointer(uint32(v.LinkType)),
				LinkUrl:    &v.LinkURL,
				Sort:       sort,
				Status:     pointy.GetPointer(uint32(v.Status)),
				CreatedAt:  pointy.GetPointer(modelx.FormatTime(v.CreatedAt, "")),
				UpdatedAt:  pointy.GetPointer(modelx.FormatTime(v.UpdatedAt, "")),
				DeletedAt:  pointy.GetPointer(modelx.FormatNullDotTime(v.DeletedAt, "")),
				StartedAt:  pointy.GetPointer(modelx.FormatNullDotTime(v.StartedAt, "")),
				EndedAt:    pointy.GetPointer(modelx.FormatNullDotTime(v.EndedAt, "")),
			})
		}
	}
	resp.Total = uint64(total)

	return resp, nil
}
